; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
; RUN: opt -O3 -S -enable-new-pm=0 < %s   | FileCheck %s --check-prefixes=ALL
; RUN: opt -passes='default<O3>' -S < %s  | FileCheck %s --check-prefixes=ALL

target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"

; PR51092: SimplifyCFG might produce duplicate PHI's/select's.
; We need to deduplicate them so that further transformations are possible.
define dso_local void @foo(i32* %in, i64 %lo, i64 %hi, i32 %ishi) #0 {
; ALL-LABEL: @foo(
; ALL-NEXT:  entry:
; ALL-NEXT:    [[TOBOOL_NOT:%.*]] = icmp eq i32 [[ISHI:%.*]], 0
; ALL-NEXT:    [[LO_HI:%.*]] = select i1 [[TOBOOL_NOT]], i64 [[LO:%.*]], i64 [[HI:%.*]]
; ALL-NEXT:    [[ARRAYIDX1:%.*]] = getelementptr inbounds i32, i32* [[IN:%.*]], i64 [[LO_HI]]
; ALL-NEXT:    [[ARRAYVAL2:%.*]] = load i32, i32* [[ARRAYIDX1]], align 4
; ALL-NEXT:    [[INC2:%.*]] = add nsw i32 [[ARRAYVAL2]], 1
; ALL-NEXT:    store i32 [[INC2]], i32* [[ARRAYIDX1]], align 4
; ALL-NEXT:    ret void
;
entry:
  %in.addr = alloca i32*, align 8
  %lo.addr = alloca i64, align 8
  %hi.addr = alloca i64, align 8
  %ishi.addr = alloca i32, align 4
  store i32* %in, i32** %in.addr, align 8
  store i64 %lo, i64* %lo.addr, align 8
  store i64 %hi, i64* %hi.addr, align 8
  store i32 %ishi, i32* %ishi.addr, align 4
  %ishi.reloaded = load i32, i32* %ishi.addr, align 4
  %tobool = icmp ne i32 %ishi.reloaded, 0
  br i1 %tobool, label %if.then, label %if.else

if.then:
  %in.reloaded = load i32*, i32** %in.addr, align 8
  %hi.reloaded = load i64, i64* %hi.addr, align 8
  %arrayidx = getelementptr inbounds i32, i32* %in.reloaded, i64 %hi.reloaded
  %arrayval = load i32, i32* %arrayidx, align 4
  %inc = add nsw i32 %arrayval, 1
  store i32 %inc, i32* %arrayidx, align 4
  br label %if.end

if.else:
  %in.reloaded2 = load i32*, i32** %in.addr, align 8
  %lo.reloaded = load i64, i64* %lo.addr, align 8
  %arrayidx1 = getelementptr inbounds i32, i32* %in.reloaded2, i64 %lo.reloaded
  %arrayval2 = load i32, i32* %arrayidx1, align 4
  %inc2 = add nsw i32 %arrayval2, 1
  store i32 %inc2, i32* %arrayidx1, align 4
  br label %if.end

if.end:
  ret void
}
